import { useState, useEffect, useRef } from "react"
import { useNotification } from "../utils/notificationContext"

function useTableDataEffect(queryAllDevicesApi, data){
  const [tableData, setTableData] = useState([])
  const [total, setTotal] = useState(0)
  const queryRef = useRef(null)
  const { openNotification } = useNotification()

  useEffect(() => {
    queryRef.current = async (isShow = false) => {
      try {
        const queryRes = await queryAllDevicesApi(data)
        console.log(queryRes);
        if (queryRes?.code === 200) {
          isShow && openNotification('获取列表成功', 'success');
          setTotal(queryRes?.total)
          const data = queryRes?.rows || queryRes?.data
          const finalData = data.map(item => {
            return {
              key: item.id,
              ...item,
            }
          })
          setTableData(finalData)
        }else{
          openNotification(queryRes?.msg, 'fail');
        }
        
      } catch (queryErr) {
        console.log(queryErr);
        openNotification('获取列表失败', 'fail');
      }
    }
    queryRef.current()
  },[queryAllDevicesApi, data, openNotification])

  return {
    tableData, 
    total,
    queryAllInfo: queryRef.current
  }  //返回key和setValue函数，key在useEffect中会被重新赋值
}
export default useTableDataEffect